<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/4
 * Time: 10:38
 */
namespace  app\api\service;

use app\lib\enum\OrderStatusEnum;
use app\lib\exception\OrderException;
use app\lib\exception\TokenException;
use think\Exception;
use app\api\model\Order as OrderModel;
use think\Loader;
use think\Log;

Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');

class Pay {

    private $orderId;
    private $orderNo;


    public function __construct($orderId){
        if(!$orderId){
            throw new Exception('订单号不能为null');
        }
        $this->orderId = $orderId;
    }


    public function pay(){
//        订单号是否存在，
//        订单号如果存在，是否和当前用户是否匹配
//        订单是否已经支付
        $this->checkOrderValid();
        //检验库存量
        $orderService = new OrderService();
        $status = $orderService->checkOrderStock($this->orderId);
        if(!$status['pass']){
            return $status;
        }
        $this->makeWxPreOrder($status['orderPrice']);
    }


    private function makeWxPreOrder($totalPrice){
        $openid = Token::getCurrentTokenVar('openid');
        if(!$openid){
            throw new TokenException();
        }
        $wxOrderData = new \WxPayUnifiedOrder();
        $wxPayConfig = new WxPayConfig();
        $orderNoStr = substr($this->orderNo,-32);
        $wxOrderData->SetOut_trade_no($orderNoStr);
        $wxOrderData->SetTrade_type('JSAPI');
        $wxOrderData->SetTotal_fee($totalPrice*100);
        $wxOrderData->SetBody('零售商贩');
        $wxOrderData->SetNotify_url('');
        $this->getPaySignatrue($wxPayConfig,$wxOrderData);
    }


    private function getPaySignatrue($wxPayConfig,$wxOrderData){
        $wxOrder = \WxPayApi::unifiedOrder($wxPayConfig,$wxOrderData);
        if($wxOrder['return_code'] != 'SUCCESS' || $wxOrder['result_code'] != 'SUCCESS'){
            Log::record($wxOrder,'error');
            Log::record('获取预支付订单失败','error');
        }
    }


    private function checkOrderValid(){
        $order = OrderModel::all(['id'=>$this->orderId]);
        if(!$order){
            throw new OrderException();
        }
        if(!Token::isValidOperate($order->user_id)){
            throw new TokenException(['msg'=>'订单与用户不匹配','errorCode'=>10003]);
        }
        if($order->status != OrderStatusEnum::UnPAID){
            throw  new OrderException(['msg'=>'订单已经支付','errorCode'=>80003]);
        }
        $this->orderNo = $order->order_no;
        return true;
    }

}